import os
import time

from django.conf import settings
from django.template import loader

from contents.models import ContentCategory
from meiduo_mall.utils.load_categories import categories_loader


def generate_static_index_html():
    """
    生成静态的主页html文件
    """
    print('%s: generate_static_index_html' % time.ctime())

    # 获取渲染页面
    categories = categories_loader()

    # 加载广告
    contents = dict()
    for category in ContentCategory.objects.all():
        contents[category.key] = category.content_set.order_by("sequence")

    # 5,拼接数据,返回响应
    context = {
        "categories": categories,
        "contents": contents
    }

    # 获取首页模板文件
    template = loader.get_template('index.html')

    # 渲染首页的html字符
    html_text = template.render(context)

    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')

    # print(file_path)

    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)

